package com.tm.szb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tm.szb.commons.R;
import com.tm.szb.dto.CategoryDTO;
import com.tm.szb.entity.Category;
import com.tm.szb.service.CategoryService;
import com.tm.szb.vo.CategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @PostMapping
    public R saveCategory(@RequestBody CategoryDTO categoryDTO){
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        categoryService.save(category);
        return R.success();
    }


    @GetMapping("page")
    public R page(Integer page,Integer pageSize){
        Page<Category> pageInfo = new Page<>(page,pageSize);
        categoryService.page(pageInfo);
        return R.success(pageInfo);
    }


    @DeleteMapping
    public R deleteCategory(@RequestParam Long id){
        categoryService.removeById(id);
        return R.success();
    }


    @PutMapping
    public R updateCategory(@RequestBody CategoryDTO categoryDTO){
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        categoryService.updateById(category);
        return R.success();
    }


    @GetMapping("list")
    public R list(@RequestParam(required = false,defaultValue = "1") Integer type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        List<Category> list = categoryService.list(wrapper);
        List<CategoryVO> categoryVOList =list.stream().map(category -> {
            CategoryVO categoryVO = new CategoryVO();
            BeanUtils.copyProperties(category,categoryVO);
            return categoryVO;
        }).collect(Collectors.toList());
        return R.success(categoryVOList);
    }
}
